//
// Copyright (c) 2007-2009 Stuart Morgan.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#import "CookieStore.h"

@interface CookieStore (Private)

// Returns an ID string for the given cookies suitable for detecting
// overlaping/conflicting cookies.
- (NSString*)idStringForCookie:(NSHTTPCookie*)cookie;

// Returns all cookies in newCookies that don't have an overlaping or
// conflicting cookie in existingCookies.
- (NSArray*)subsetOfCookies:(NSArray*)newCookies
               notInCookies:(NSArray*)existingCookies;

@end

@implementation CookieStore

- (void)dealloc {
  [mCookies release];
  [mLastError release];
  [super dealloc];
}

- (BOOL)loadCookies {
  [self willChangeValueForKey:@"cookies"];
  [mCookies autorelease];
  mCookies = [[self storedCookies] mutableCopy];
  [self didChangeValueForKey:@"cookies"];
  return mCookies != nil;
}

- (NSArray*)cookies {
  return mCookies;
}

- (BOOL)addCookies:(NSArray*)cookies {
  NSArray* newCookies = [self subsetOfCookies:cookies notInCookies:mCookies];
  [self willChangeValueForKey:@"cookies"];
  [mCookies addObjectsFromArray:cookies];
  [self didChangeValueForKey:@"cookies"];
  return [self addNewCookies:newCookies];
}

- (NSString*)idStringForCookie:(NSHTTPCookie*)cookie {
  return [NSString stringWithFormat:@"%@::%@::%@",
             [cookie domain], [cookie path], [cookie name]];
}

- (NSArray*)subsetOfCookies:(NSArray*)newCookies
               notInCookies:(NSArray*)existingCookies {
  // Build a set from the existing cookies for fast conflict detection
  NSMutableSet* existingCookieSet =
      [NSMutableSet setWithCapacity:[existingCookies count]];
  NSEnumerator* cookieEnumerator = [existingCookies objectEnumerator];
  NSHTTPCookie* cookie;
  while ((cookie = [cookieEnumerator nextObject])) {
    [existingCookieSet addObject:cookie];
  }

  NSMutableArray* subset = [NSMutableArray array];
  cookieEnumerator = [newCookies objectEnumerator];
  while ((cookie = [cookieEnumerator nextObject])) {
    if (![existingCookieSet containsObject:[self idStringForCookie:cookie]]) {
      [subset addObject:cookie];
    }
  }
  return subset;
}

- (NSError*)lastError {
  return mLastError;
}

- (void)setLastErrorWithTitleKey:(NSString*)titleKey
                      messageKey:(NSString*)messageKey {
  NSDictionary* errorDict = [NSDictionary dictionaryWithObjectsAndKeys:
        NSLocalizedString(titleKey, nil), NSLocalizedDescriptionKey,
      NSLocalizedString(messageKey, nil), NSLocalizedFailureReasonErrorKey,
                                          nil];
  [mLastError autorelease];
  mLastError = [[NSError alloc] initWithDomain:@"CookieStore"
                                          code:0
                                      userInfo:errorDict];
}

- (BOOL)addNewCookies:(NSArray*)cookies {
  [NSException raise:@"UnimplementedMethod"
              format:@"addNewCookies: not implemented on %@", self];
  return NO;
}

- (NSArray*)storedCookies {
  [NSException raise:@"UnimplementedMethod"
              format:@"storedCookies not implemented on %@", self];
  return NO;
}

@end
